package com.micro.school.common.security.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.AsyncHandlerInterceptor;
import com.micro.school.common.core.constant.SecurityConstants;
import com.micro.school.common.core.context.SecurityContextHolder;
import com.micro.school.common.core.utils.ServletUtils;
import com.micro.school.common.core.utils.StringUtils;
import com.micro.school.common.security.auth.AuthUtil;
import com.micro.school.common.security.utils.SecurityUtils;
import com.micro.school.system.api.model.LoginUser;

import java.util.Enumeration;

/**
 * 自定义请求头拦截器，将Header数据封装到线程变量中方便获取
 * 注意：此拦截器会同时验证当前用户有效期自动刷新有效期
 *
 * @author upupgo
 */
@Slf4j
public class HeaderInterceptor implements AsyncHandlerInterceptor
{
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
    {
        if (!(handler instanceof HandlerMethod))
        {
            return true;
        }
        String header = ServletUtils.getHeader(request, SecurityConstants.DETAILS_USER_ID);
        String header1 = ServletUtils.getHeader(request, SecurityConstants.DETAILS_USERNAME);
        String header2 = ServletUtils.getHeader(request, SecurityConstants.USER_KEY);
        String header3 = ServletUtils.getHeader(request, SecurityConstants.DETAILS_TENANT_ID);
        String header4 = ServletUtils.getHeader(request, SecurityConstants.DETAILS_CAMPUS_ID);
        String header5 = ServletUtils.getHeader(request, SecurityConstants.DETAILS_COLLEGE_ID);
        String header6 = ServletUtils.getHeader(request, SecurityConstants.DETAILS_IS_HIDE);

        //yourMethod(request);

        SecurityContextHolder.setUserId(ServletUtils.getHeader(request, SecurityConstants.DETAILS_USER_ID));
        SecurityContextHolder.setUserName(ServletUtils.getHeader(request, SecurityConstants.DETAILS_USERNAME));
        SecurityContextHolder.setUserKey(ServletUtils.getHeader(request, SecurityConstants.USER_KEY));
        SecurityContextHolder.setUserTenantId(ServletUtils.getHeader(request, SecurityConstants.DETAILS_TENANT_ID));
        SecurityContextHolder.setUserCompusId(ServletUtils.getHeader(request, SecurityConstants.DETAILS_CAMPUS_ID));
        SecurityContextHolder.setUserCollegeId(ServletUtils.getHeader(request, SecurityConstants.DETAILS_COLLEGE_ID));
        SecurityContextHolder.setUserIdcardState(ServletUtils.getHeader(request, SecurityConstants.DETAILS_IS_HIDE));

//        log.info("SecurityContextHolder.getUserTenantId: {}", SecurityContextHolder.getUserTenantId());


       String details_tenantid = ServletUtils.getHeader(request, SecurityConstants.DETAILS_TENANTID);
       if(StringUtils.isEmpty(SecurityContextHolder.get(SecurityConstants.DETAILS_TENANTID)) && StringUtils.isNotEmpty(details_tenantid)){
           SecurityContextHolder.setUserTenantId(details_tenantid);
       }

        String details_campusid = ServletUtils.getHeader(request, SecurityConstants.DETAILS_CAMPUSID);
        if(StringUtils.isEmpty(SecurityContextHolder.get(SecurityConstants.DETAILS_CAMPUS_ID)) && StringUtils.isNotEmpty(details_campusid)){
            SecurityContextHolder.setUserCompusId(details_campusid);
        }

        String token = SecurityUtils.getToken();
        if (StringUtils.isNotEmpty(token))
        {
            LoginUser loginUser = AuthUtil.getLoginUser(token);
            if (StringUtils.isNotNull(loginUser))
            {
                AuthUtil.verifyLoginUserExpire(loginUser);
                SecurityContextHolder.set(SecurityConstants.LOGIN_USER, loginUser);
            }
        }
        return true;
    }
    public void yourMethod(HttpServletRequest request) {
        Enumeration<String> headerNames = request.getHeaderNames();

        if (headerNames != null) {
            while (headerNames.hasMoreElements()) {
                String headerName = headerNames.nextElement();
                Enumeration<String> headers = request.getHeaders(headerName);
                StringBuilder headerValues = new StringBuilder();

                // 有些 Header 可能有多个值（如 Accept）
                while (headers.hasMoreElements()) {
                    if (headerValues.length() > 0) headerValues.append(", ");
                    headerValues.append(headers.nextElement());
                }

                log.info("Header: {} = {}", headerName, headerValues.toString());
            }
        } else {
            log.info("No headers found in the request.");
        }
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception
    {
        SecurityContextHolder.remove();
    }
}
